/**
 * 
 */
package cn.nawang.ebeim.client;

import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.nawang.ebeim.client.bean.DownloadProcessBarBean;
import cn.nawang.ebeim.client.bean.UserBehaviorsLog;
import cn.nawang.ebeim.client.util.DbUpDownloadUtil;
import cn.nawang.ebeim.client.util.DownloadProcessBarList;
import cn.nawang.ebeim.client.util.UserBehaviorsUploadUtils;

/**
 * @ClassName: DownloadProcessBarThread
 * @Description: 下载进度条线程
 * @author zhangjf
 * @date 2015年10月9日 下午3:40:51
 * @version v1.0
 */
public class DownloadProcessBarThread implements Runnable{
  
  private static final Logger LOG = LoggerFactory.getLogger(DownloadProcessBarThread.class);

  @Override
  public void run() {
    
    while(!AppMain.stopFlag.get()){
      for (String key : DownloadProcessBarList.total.keySet()) {
        DownloadProcessBarBean bean = DbUpDownloadUtil.getDownloadProcessBarByNid(DbUpDownloadUtil.PROCESS_BAR_STATUS_RUNNING,key);
        LOG.info("DownloadProcessBarBean:"+bean);
        if(bean!=null){
          if(bean.getCount() >= bean.getTotal() || bean.getOkSum()+bean.getErrorSum() >= bean.getFileSum()){
            DbUpDownloadUtil.updateDownloadProcessBarStatusByNid(DbUpDownloadUtil.PROCESS_BAR_STATUS_SUCCESS,bean.getNid());
            Iterator it = DownloadProcessBarList.total.keySet().iterator();
            while(it.hasNext()) {
              String nid = (String) it.next();
              if(nid.equals(key)){
                it.remove();
              }
            }
            UserBehaviorsUploadUtils.uploadAllFile(bean.getDsId(), UserBehaviorsLog.ACTION_DOWANLOAD);
          }else{
            DbUpDownloadUtil.updateDownloadProcessBarCountByNid(DownloadProcessBarList.total.get(key), bean.getNid());
            LOG.info("summation:"+(DownloadProcessBarList.total.get(key)));
          }
        }
      }
      
      try {
        Thread.sleep(2500);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    
  }

}
